package com.qipay.api.qrcode.controller;

import com.qipay.api.BaseController;

import com.qipay.baas.model.Cp;
import com.qipay.baas.model.CpInfo;
import com.qipay.cp.CpService;
import com.qipay.cp.config.CpAccountStateEnum;
import com.qipay.cpinfo.service.CpInfoService;
import com.qipay.order.service.OrderService;

import com.qipay.security.sign.service.SignService;
import com.qipay.utils.SignSortMD5Utils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.validation.constraints.NotNull;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * com.qipay.api.qrcode.controller
 *
 * @author Administrator Ansen
 * @date 2017/10/30
 */
@RestController
@RequestMapping("/common")
public class QRCodePayController extends BaseController {

    protected final Log logger = LogFactory.getLog(this.getClass());

    @Value("${api.response.sign.name}")
    private String sigKey;

    @Autowired
    SignService signService;

    @Autowired
    CpService cpService;

    @Autowired
    CpInfoService cpInfoService;

    @Autowired
    OrderService orderService;


    @RequestMapping(value = "/cp/pay/qrcode", method = RequestMethod.GET)
    public ModelAndView createQRCode(
            @RequestParam @NotNull String mchid,
            @RequestParam @NotNull String sign,
            HttpServletRequest request
    ) {

        Cp cp = cpService.getOneByAppId(mchid);
        Assert.notNull(cp, "无法找到CP的信息");
        Assert.isTrue(Objects.equals(CpAccountStateEnum.ENABLED.getState(), cp.getAccountState()),
                "该CP还未开启支付或已被禁用");

        Map<String, Object> params = new HashMap<>(2);
        params.put("mchid", mchid);

        String mySign = SignSortMD5Utils.getSign(params, cp.getSecretId(), sigKey);
        if (!StringUtils.equals(sign, mySign)) {
            logger.warn("签名不一致:fromSig:" + sign + ", mysig:" + mySign);
        }
        Assert.isTrue(StringUtils.equals(sign, mySign), "无效的签名信息");

        ModelAndView modelAndView = createModelAndView("cp-qr-pay");
        Map<String, Object> viewParams = new HashMap<>(4);

        modelAndView.addObject("mch_id", cp.getAppId());
        viewParams.put("mch_id", cp.getAppId());

        String outTradeNo = orderService.createOrder();
        modelAndView.addObject("out_trade_no", outTradeNo);
        viewParams.put("out_trade_no", outTradeNo);

        modelAndView.addObject("body", "移动支付");
        viewParams.put("body", "移动支付");

        String nonceStr = String.valueOf(System.currentTimeMillis());
        modelAndView.addObject("nonce_str", nonceStr);
        viewParams.put("nonce_str", nonceStr);

        String viewSign = SignSortMD5Utils.getSign(viewParams, cp.getSecretId());
        modelAndView.addObject("sign", viewSign);

        CpInfo cpInfo = cpInfoService.get(cp.getId());
        Assert.notNull(cpInfo, "无法找到CP的信息");

        modelAndView.addObject("mch_name", cpInfo.getName());

        return modelAndView;
    }

}
